import 'package:craze/models/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:craze/common/index.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:go_router/go_router.dart';
import 'package:craze/stores/video_store.dart';
import 'package:craze/stores/team_store.dart';

class CollectView extends StatefulWidget {
  const CollectView({super.key});

  @override
  State<CollectView> createState() => _CollectViewState();
}

class _CollectViewState extends State<CollectView> {
  final PageController _pageController = PageController();
  int _currentIndex = 0;

  final AuthStore _authStore = getIt<AuthStore>();
  final CollectionStore _collectionStore = getIt<CollectionStore>();
  final UserService _userService = getIt<UserService>();
  final TeamStore _teamStore = getIt<TeamStore>();
  final VideoStore _videoStore = getIt<VideoStore>();

  bool _isLoading = true;
  String? _errorMessage;

  @override
  void initState() {
    super.initState();
    _loadCollections();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 页面展示时刷新收藏数据
    _loadCollections();
  }

  Future<void> _loadCollections() async {
    if (!mounted) return;

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      if (_authStore.isLoggedIn) {
        await _collectionStore.loadUserCollections();
      } else {
        setState(() {
          _errorMessage = "Please login first";
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _errorMessage = "Failed to load collections: ${e.toString()}";
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  void _onPageChanged(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  void _onTabTapped(int index) {
    _pageController.animateToPage(
      index,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Header with back button and centered title
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    // Back button aligned to the left
                    Align(
                      alignment: Alignment.centerLeft,
                      child: IconButton(
                        icon: Icon(
                          Icons.arrow_back_ios,
                          color: Colors.white,
                          size: 24.sp,
                        ),
                        onPressed: () => Navigator.of(context).pop(),
                        padding: EdgeInsets.zero,
                        constraints: BoxConstraints(),
                      ),
                    ),
                    // Title centered
                    Text(
                      'Collect',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 24.sp,
                        fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ],
                ),
              ),

              // Custom Tab Bar
              Padding(
                padding: EdgeInsets.only(top: 16.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildTabItem('Team Up', 0),
                    _buildTabItem('Community', 1),
                    _buildTabItem('Video', 2),
                  ],
                ),
              ),

              // Page Content
              Expanded(
                child:
                    _isLoading
                        ? _buildLoadingView()
                        : _errorMessage != null
                        ? _buildErrorView()
                        : !_authStore.isLoggedIn
                        ? _buildLoginRequiredView()
                        : PageView(
                          controller: _pageController,
                          onPageChanged: _onPageChanged,
                          children: [
                            Observer(builder: (_) => _buildTeamUpTab()),
                            Observer(builder: (_) => _buildCommunityTab()),
                            Observer(builder: (_) => _buildVideoTab()),
                          ],
                        ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLoadingView() {
    return Center(child: CircularProgressIndicator(color: Colors.white));
  }

  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, color: Colors.white, size: 60.sp),
          SizedBox(height: 16.h),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 30.w),
            child: Text(
              _errorMessage ?? 'Something went wrong',
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white, fontSize: 16.sp),
            ),
          ),
          SizedBox(height: 24.h),
          ElevatedButton(
            onPressed: _loadCollections,
            style: ElevatedButton.styleFrom(
              backgroundColor: MyColors.blue,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.r),
              ),
            ),
            child: Text('Retry', style: TextStyle(color: Colors.white)),
          ),
        ],
      ),
    );
  }

  Widget _buildLoginRequiredView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.account_circle_outlined, color: Colors.white, size: 80.sp),
          SizedBox(height: 24.h),
          Text(
            'Login Required',
            style: TextStyle(
              color: Colors.white,
              fontSize: 24.sp,
              fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
              fontWeight: FontWeight.w400,
            ),
          ),
          SizedBox(height: 16.h),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 40.w),
            child: Text(
              'You need to log in to view your collections',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white.withAlpha(180),
                fontSize: 16.sp,
                fontFamily: GoogleFonts.inter().fontFamily,
              ),
            ),
          ),
          SizedBox(height: 40.h),
          GestureDetector(
            onTap: () {
              LoginDialog.show(context);
            },
            child: Container(
              width: 200.w,
              height: 50.h,
              decoration: BoxDecoration(
                color: MyColors.blue,
                borderRadius: BorderRadius.circular(25.r),
              ),
              alignment: Alignment.center,
              child: Text(
                'Log In',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18.sp,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // Tab item with fixed indicator
  Widget _buildTabItem(String text, int index) {
    bool isSelected = _currentIndex == index;

    return GestureDetector(
      onTap: () => _onTabTapped(index),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            text,
            style: TextStyle(
              color: isSelected ? Colors.white : Colors.grey,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
            ),
          ),
          SizedBox(height: 6.h),
          Container(
            width: 12.w,
            height: 4.h,
            decoration: BoxDecoration(
              color: isSelected ? Colors.white : Colors.transparent,
              borderRadius: BorderRadius.circular(2.r),
            ),
          ),
        ],
      ),
    );
  }

  // Team Up Tab - 2 columns grid of team cards
  Widget _buildTeamUpTab() {
    final teams = _collectionStore.collectedTeams;

    if (teams.isEmpty) {
      return _buildEmptyView(
        "No collected teams",
        "Collect interesting teams to see them here",
      );
    }

    return Padding(
      padding: EdgeInsets.all(20.w),
      child: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 8.w,
          mainAxisSpacing: 16.h,
          childAspectRatio: 183 / 148,
        ),
        itemCount: teams.length,
        itemBuilder: (context, index) {
          return _createTeamCard(teams[index]);
        },
      ),
    );
  }

  // Community Tab - 1 column list of share posts
  Widget _buildCommunityTab() {
    final shares = _collectionStore.collectedShares;

    if (shares.isEmpty) {
      return _buildEmptyView(
        "No collected posts",
        "Collect interesting posts to see them here",
      );
    }

    return Padding(
      padding: EdgeInsets.all(20.w),
      child: ListView.builder(
        itemCount: shares.length,
        itemBuilder: (context, index) {
          return Padding(
            padding: EdgeInsets.only(bottom: 20.h),
            child: _buildSharePostCard(shares[index]),
          );
        },
      ),
    );
  }

  // Video Tab - 1 column list of video thumbnails
  Widget _buildVideoTab() {
    final videos = _collectionStore.collectedVideos;

    if (videos.isEmpty) {
      return _buildEmptyView(
        "No collected videos",
        "Collect interesting videos to see them here",
      );
    }

    return Padding(
      padding: EdgeInsets.all(20.w),
      child: ListView.builder(
        itemCount: videos.length,
        itemBuilder: (context, index) {
          return _buildVideoCard(videos[index]);
        },
      ),
    );
  }

  Widget _buildEmptyView(String title, String subtitle) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(MyImages.empty, height: 120.h),
          SizedBox(height: 16.h),
          Text(
            title,
            style: TextStyle(
              color: Colors.white,
              fontSize: 16.sp,
              fontFamily: GoogleFonts.inter().fontFamily,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            subtitle,
            style: TextStyle(
              color: Colors.white.withAlpha(153),
              fontSize: 14.sp,
              fontFamily: GoogleFonts.inter().fontFamily,
              fontWeight: FontWeight.w400,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  // Team Card Widget
  Widget _createTeamCard(TeamModel team) {
    // 获取团队发起人信息
    final initiator = _userService.getUserById(team.initiatorId);
    final initiatorName = initiator?.name ?? 'Unknown';

    // 格式化日期
    final formattedDate =
        "${team.departureDate.month}/${team.departureDate.day}";

    // 获取团队成员头像
    List<Widget> memberAvatars = [];
    for (int i = 0; i < team.memberIds.length; i++) {
      if (i < team.maxMembers) {
        final member = _userService.getUserById(team.memberIds[i]);
        final avatarUrl = member?.avatar ?? MyImages.touxiang1;

        memberAvatars.add(
          Padding(
            padding: EdgeInsets.only(right: 2.w),
            child: CircleAvatar(
              radius: 12.r,
              backgroundImage: AssetImage(avatarUrl),
            ),
          ),
        );
      }
    }

    // 添加剩余的空位
    for (int i = team.memberIds.length; i < team.maxMembers; i++) {
      memberAvatars.add(
        Padding(
          padding: EdgeInsets.only(right: 2.w),
          child: CircleAvatar(
            radius: 12.r,
            backgroundColor: Colors.black38,
            child: Icon(Icons.add, color: Colors.white, size: 16.r),
          ),
        ),
      );
    }

    return GestureDetector(
      onTap: () {
        // 先设置选中团队，再跳转
        _teamStore.selectTeam(team.id);
        GoRouter.of(context).push('/team');
      },
      child: Container(
        width: 183.w,
        height: 148.h,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16.r),
          image: DecorationImage(
            image: AssetImage(MyImages.teamCommonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: Stack(
          children: [
            // 渐变背景
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12.r),
                border: Border.all(color: MyColors.blue, width: 1.w),
              ),
              child: Padding(
                padding: EdgeInsets.all(6.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Spacer(),
                    // Team info with smaller text for grid view
                    Text(
                      'Initiator: $initiatorName',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    SizedBox(height: 2.h),
                    Text(
                      'Departure Date: $formattedDate',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    SizedBox(height: 2.h),
                    Text(
                      'Number Of People: ${team.memberIds.length}/${team.maxMembers}',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                    const Spacer(),
                    // Member avatars
                    Row(children: memberAvatars),
                    const Spacer(),
                    // Team name
                    Text(
                      team.name,
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w700,
                        fontFamily: GoogleFonts.inter().fontFamily,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                    const Spacer(),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Share Post Card Widget
  Widget _buildSharePostCard(SharePostModel post) {
    final author = _userService.getUserById(post.userId);
    final userName = author?.name ?? 'Unknown';
    final userAvatar = author?.avatar ?? MyImages.touxiang1;

    // 获取当前用户
    final currentUser = _authStore.currentUser;
    // 关注状态
    final isFollowed =
        currentUser != null &&
        author != null &&
        currentUser.followingIds.contains(author.id);
    // 收藏状态
    final isCollected = _collectionStore.isShareInCollection(post.id);

    // 获取浏览者头像
    List<Widget> viewerAvatars = [];
    for (int i = 0; i < post.viewerIds.length && i < 4; i++) {
      final viewer = _userService.getUserById(post.viewerIds[i]);
      final avatarUrl = viewer?.avatar ?? MyImages.touxiang1;
      viewerAvatars.add(
        Positioned(
          left: i * 25.w,
          child: Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: MyColors.blue, width: 1.w),
            ),
            child: CircleAvatar(
              radius: 18.r,
              backgroundImage: AssetImage(avatarUrl),
            ),
          ),
        ),
      );
    }

    return GestureDetector(
      onTap: () {
        // 跳转到分享详情页，带id参数
        GoRouter.of(context).push('/share-detail/${post.id}');
      },
      child: Container(
        width: 374.w,
        decoration: BoxDecoration(
          color: Colors.white.withAlpha(25),
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 14.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // First row: avatar, username, follow button, collect icon
              Row(
                children: [
                  // Avatar
                  CircleAvatar(
                    radius: 22.r,
                    backgroundImage: AssetImage(userAvatar),
                  ),
                  SizedBox(width: 8.w),
                  // Username
                  Text(
                    userName,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w400,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                    ),
                  ),
                  SizedBox(width: 10.w),
                  // Follow button
                  GestureDetector(
                    onTap: () async {
                      if (currentUser == null || author == null) {
                        LoginDialog.show(
                          context,
                          title: 'Login',
                          description: 'Please login first',
                        );
                        return;
                      }
                      if (isFollowed) {
                        await _userService.unfollowUser(
                          currentUser.id,
                          author.id,
                        );
                      } else {
                        await _userService.followUser(
                          currentUser.id,
                          author.id,
                        );
                      }
                      // 刷新当前用户数据
                      _authStore.currentUser = _userService.getUserById(
                        currentUser.id,
                      );
                      // 触发UI刷新
                      setState(() {});
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 8.w,
                        vertical: 4.h,
                      ),
                      decoration: BoxDecoration(
                        color: isFollowed ? Colors.grey : Colors.blue,
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Text(
                        isFollowed ? 'followed' : '+follow',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 13.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                  const Spacer(),
                  // 收藏按钮
                  GestureDetector(
                    onTap: () async {
                      await _collectionStore.toggleShareCollection(post.id);
                      setState(() {});
                    },
                    child: Container(
                      width: 37.w,
                      height: 37.w,
                      decoration: ShapeDecoration(
                        color: Colors.white.withOpacity(0.06),
                        shape: OvalBorder(),
                      ),
                      child: Icon(
                        isCollected
                            ? MyIcons.iconCollectFill
                            : MyIcons.iconCollect,
                        color: isCollected ? Colors.red : Colors.white,
                        size: 20.sp,
                      ),
                    ),
                  ),
                ],
              ),
              SizedBox(height: 12.h),

              // Second row: description text
              Text(
                post.description,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14.sp,
                  height: 1.5,
                  fontFamily: GoogleFonts.inter().fontFamily,
                ),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              SizedBox(height: 12.h),

              // Third row: images
              SizedBox(
                height: 113.h,
                child:
                    post.imageUrls.isNotEmpty
                        ? Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: List.generate(
                            post.imageUrls.length > 3
                                ? 3
                                : post.imageUrls.length,
                            (index) => Container(
                              width: 113.w,
                              height: 113.h,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(12.r),
                                image: DecorationImage(
                                  image: AssetImage(post.imageUrls[index]),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                          ),
                        )
                        : Center(
                          child: Text(
                            'No images',
                            style: TextStyle(
                              color: Colors.white.withAlpha(153),
                              fontSize: 14.sp,
                            ),
                          ),
                        ),
              ),
              SizedBox(height: 12.h),

              // Fourth row: viewed avatars and report button
              Row(
                children: [
                  // Viewed avatars stack
                  SizedBox(
                    width: 120.w,
                    height: 37.h,
                    child:
                        viewerAvatars.isEmpty
                            ? Center(
                              child: Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 10.w,
                                  vertical: 5.h,
                                ),
                                decoration: BoxDecoration(
                                  color: Colors.white.withOpacity(0.2),
                                  borderRadius: BorderRadius.circular(15.r),
                                ),
                                child: Text(
                                  'No viewers yet',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 10.sp,
                                    fontFamily: GoogleFonts.inter().fontFamily,
                                  ),
                                ),
                              ),
                            )
                            : Stack(children: viewerAvatars),
                  ),
                  SizedBox(width: 4.w),
                  // "Already viewed" text
                  Text(
                    viewerAvatars.isEmpty ? '' : 'Already viewed',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 11.sp,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      fontWeight: FontWeight.w400,
                      height: 1.36,
                    ),
                  ),
                  const Spacer(),
                  // Report button
                  Container(
                    padding: EdgeInsets.all(8.r),
                    decoration: BoxDecoration(
                      color: MyColors.iconDark,
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      MyIcons.iconReport,
                      color: Colors.white,
                      size: 20.sp,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  // Video Card Widget
  Widget _buildVideoCard(VideoModel video) {
    return GestureDetector(
      onTap: () {
        // 先设置当前视频，再跳转
        _videoStore.selectVideo(video.id);
        GoRouter.of(context).push('/video');
      },
      child: Padding(
        padding: EdgeInsets.only(bottom: 15.h),
        child: Stack(
          children: [
            Container(
              height: 200.h,
              width: double.infinity,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16.r),
                image: DecorationImage(
                  image: AssetImage(video.thumbnailUrl),
                  fit: BoxFit.cover,
                ),
              ),
              child: Center(
                child: Container(
                  height: 50.w,
                  width: 50.w,
                  decoration: BoxDecoration(
                    color: Colors.black45,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.play_arrow,
                    color: Colors.white,
                    size: 36.sp,
                  ),
                ),
              ),
            ),

            // 视频标题
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(16.r),
                    bottomRight: Radius.circular(16.r),
                  ),
                  gradient: LinearGradient(
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                    colors: [Colors.transparent, Colors.black.withOpacity(0.8)],
                  ),
                ),
                child: Text(
                  video.title,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
